define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"UtilDir/loading",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock, Loading){

    var sysPath =  getServer() + "/static/app/fxpg/fxPreestimateIntegration";

    var fxPreestimateIntegrationFormHtml = sysPath + "/views/fxPreestimateIntegrationForm.html";

	var getBoundaryController = function () {
		return getServer() + "/boundary";
	};

	var getFxMiddleResultsController = function(){
		return getServer() + "/fxMiddleResults";
	};
	var getFxPreestimateIntegrationController = function(){
		return getServer() + "/fx/fxPreestimateResults";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		initTimeSelect();
		initMagnitudeSelect();
		initEstimateObjectSelect();
		initColorBar();
		initMap();
		formValidator();
	};

	var initTimeSelect = function () {
		$.ajax({
			url: getFxMiddleResultsController() + "/getValidDictItemsByDictCode/" + "year",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yearSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initMagnitudeSelect = function () {
		$.ajax({
			url: getFxMiddleResultsController() + "/getValidDictItemsByDictCode/" + "magnitude",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("magnitudeSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initEstimateObjectSelect = function () {
		$.ajax({
			url: getFxMiddleResultsController() + "/getValidDictItemsByDictCode/" + "estimateObject",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("estimateSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
			getFxPreestimateResults();
        });
        $("#btnReset").click(function () {
            $("#yearSelect").val("");
			$("#magnitudeSelect").val("");
			$("#estimateSelect").val("");
        });
		$("#btnExport").click(function () {
			exportFxPreestimateResults();
		});
	};
	var formValidator = function () {
		$("#searchForm").validate({
			rules: {
				estimateSelect: {
					required: true
				}
			},
			messages: {
				estimateSelect: {
					required: "请选择评估对象!"
				}
			}
		});
	};
/*
	death_num_after//预估死亡人数（修正后）
	injury_num_after//预估受伤人数（修正后）
	urgent_arrange_num//需紧急安置数
	unit_rescue_num//救援部队队伍（人）
	medical_rescue_num//医疗救援(人)
	tent_num//预估帐篷总数*/
	/*deathNumAfter
	injuryNumAfter
	urgentArrangeNum
	unitRescueNum
	medicalRescueNum
	tentNum*/
	var getFxPreestimateResults = function(){
		console.log("查询预估结果");
		var year = $("#yearSelect").val();
		var magnitude = $("#magnitudeSelect").val();
		var estimateObj = $("#estimateSelect").val();
		if (!$("#searchForm").valid()) return;
		loading.show();
		$.ajax({
			url: getFxPreestimateIntegrationController() + "/getFxPreestimateResults?year=" + year + "&magnitude=" + magnitude,
			type: "GET",
			dataType: "json",
			success: function(data) {
				//loading.close();
				global_points = []; global_areaIsFinished = {};
				console.log(estimateObj);
				console.log(data);
				var area2obj = {}, obj_value = 0, districts, location, district = "", province = "", city = "", area = "", min_value = Infinity, max_value = 0;
				if (data && data.length) {
					for (let i = 0; i < data.length; i++) {
						district = data[i].province;
						districts = district.split("-");
						province = districts[0];
						city = districts[1];
						area = districts[2];
						location = data[i].location;
						console.log(area , location);
						if (area != location) continue;
						area = district;

						obj_value = parseFloat(data[i][estimateObj]);
						obj_value = obj_value || 0;
						!area2obj[area] ? (area2obj[area] = obj_value) : (area2obj[area] += obj_value);
						global_areaIsFinished[area] = false;
					}
					var _value = 0, evaluate_res = 0;
					for (var key in area2obj) {
						_value = area2obj[key];
						(min_value > _value) && (min_value = _value); (max_value < _value) && (max_value = _value);
					}
					changeColorLabel(min_value, max_value);
					tdMap.clearOverLays();
					console.log(area2obj);
					for (let key in area2obj) {
						evaluate_res = area2obj[key];
						//console.log("evaluate_res: ", evaluate_res);
						renderDistrictByEvaluation(evaluate_res, key, min_value, max_value);
					}
				} else {
					Util.alert("查询无数据!");
				}
			}
		});
	};
	var renderDistrictByEvaluation = function (evaluation, district, min, max) {
		var districts = district.split("-"), province = districts[0], city = districts[1], areaName = districts[2];
		var formData = {province: province, city: city, area: areaName};
		$.ajax({
			url: getBoundaryController() + "/getSingleAreaBoundary",
			type: "POST",
			data: formData,
			success: function (coords) {
				//console.log(coords);
				coords = coords[areaName];
				global_areaIsFinished[district] = true;
				if (coords) {
					var lonlats = coords.split(";"), lonlat, lon = 0, lat = 0, points = [];
					for (var i = 0;i < lonlats.length;i++) {
						lonlat = lonlats[i].split(",");
						lon = parseFloat(lonlat[0]); lat = parseFloat(lonlat[1]);
						points.push(new T.LngLat(lon, lat));
					}
					global_points = global_points.concat(points);
					var color = getPolygonColorByValue(evaluation, min, max);
					var areaPolygon = new T.Polygon(points, {
						color: "#0000ff",
						weight: 1,
						opacity: 0.5,
						fillColor: color,
						fillOpacity: 0.5
					});
					tdMap.addOverLay(areaPolygon);

					taskIsFinish(global_areaIsFinished) && (tdMap.setViewport(global_points), loading.close(), console.log("&&&&&&"));
				} else {
					loading.close();
					Util.alert("【" + areaName + "】无边界数据!");
				}
			}
		});

	};
	var getPolygonColorByValue = function (polygon_value, min, max) {
		min = parseFloat(min) || 0; max = parseFloat(max) || 1;
		var img_bar_width = 150, factor = img_bar_width / 360;
		var value_per_pixel = (max - min) / img_bar_width;
		var pixel_seg = (polygon_value - min) / value_per_pixel;
		var position = img_bar_width - pixel_seg, hue_value = 360 - (img_bar_width - pixel_seg) / factor;
		//fx_REQADCPicker.children(":first").css("top", position + "px");
		var col = fx_PEIPicker.getColorByHue(hue_value);
		//console.log("hue_value: ", hue_value);
		return "#" + col;
	};
	var changeColorLabel = function (min, max) {
		min = parseFloat(min) || 0; max = parseFloat(max) || 1;
		(min == max) && (min = 0, max = 1);
		var value_label_doms = $("#fx-PEI-color-picker").siblings();
		value_label_doms.eq(0).html(min); value_label_doms.eq(1).html((min + max) / 2); value_label_doms.eq(2).html(max);
		console.log("min: ", min, "max: ", max);
	};
	var initColorBar = function () {
		fx_PEIPicker = $('#fx-PEI-color-picker').colpick({
			flat:true,
			layout:'hex',//rgbhex
			submit:false,
			showEvent: 'focus'
		});
	};

	var loading = Loading({text : "正在查询数据..."});
	var tdMap, fx_PEIPicker, global_points = [], global_areaIsFinished = {};
	var initMap = function () {
		var mapH = document.body.clientHeight - $(".pd-search-container").height() - 20;
		$("#fx-PEI-mapDiv").height(mapH);

		var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
			projection: 'EPSG:4326',
			minZoom: 4,
			layers: [vec_layer, cva_layer]
		};
		tdMap = new T.Map('fx-PEI-mapDiv', config), zoom = 4;
		tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);
	};
	var taskIsFinish = function (obj) {
		for (var _key in obj) if (!obj[_key]) return false;
		return true;
	}

	var exportFxPreestimateResults = function () {
		var year = $("#yearSelect").val(), magnitude = $("#magnitudeSelect").val(),estimate=$("#estimateSelect").val();
		window.location.href = getFxPreestimateIntegrationController() + "/export?year=" + year + "&magnitude=" + magnitude + "&estimate=" + estimate;
	};

	return {
		init:init
	};
});
